<template>
  <view class="messages-container">
    <!-- 选项卡 -->
    <view class="tab-bar-top">
      <text :class="{'active-tab': currentTab === 'todo'}" @click="currentTab = 'todo'">待生产列表</text>
      <text :class="{'active-tab': currentTab === 'done'}" @click="currentTab = 'done'">生产中列表</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">加载中...</view>
    
    <!-- 空数据提示 -->
    <view v-else-if="currentTab === 'todo' && todoList.length === 0" class="empty">暂无待生产订单</view>
    <view v-else-if="currentTab === 'done' && doneList.length === 0" class="empty">暂无生产中订单</view>

    <!-- 生产列表 -->
    <view v-if="currentTab === 'todo' && !loading">
      <view v-for="item in todoList" :key="item.id" class="message-item">
        <view class="item-header">
          <text class="order-code">{{ item.orderCode }}</text>
          <text class="status-tag todo">待生产</text>
        </view>
        <text class="product-name">{{ item.productName }}</text>
        <view class="item-details">
          <text>车间：{{ item.workshopName }}</text>
          <text>数量：{{ item.allocatedQuantity }}/{{ item.quantity }}</text>
        </view>
      </view>
    </view>

    <view v-if="currentTab === 'done' && !loading">
      <view v-for="item in doneList" :key="item.id" class="message-item">
        <view class="item-header">
          <text class="order-code">{{ item.orderCode }}</text>
          <text class="status-tag doing">生产中</text>
        </view>
        <text class="product-name">{{ item.productName }}</text>
        <view class="item-details">
          <text>负责人：{{ item.managerName }}</text>
          <text>进度：{{ calcProgress(item) }}%</text>
          <text>剩余数量：{{ calcRemainingQuantity(item) }}</text> <!-- 新增：剩余数量 -->
        </view>
      </view>
    </view>

    <pveVue/>
  </view>
</template>

<script>
import pveVue from '../components/pve.vue';

export default {
  components: { pveVue },
  data() {
    return {
      currentTab: 'todo',
      activeTab: 'messages',
      todoList: [],
      doneList: [],
      loading: true
    };
  },
  created() {
    this.fetchMessages();
  },
  methods: {
    // 获取车间ID
    async getWorkshopId() {
      try {
        const userIdInfo = uni.getStorageSync('userIdInfo');
        if (!userIdInfo || !userIdInfo.userId) {
          uni.showToast({ title: '未登录，请重新登录', icon: 'none' });
          return null;
        }
        if (Date.now() > userIdInfo.expiration) {
          uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
          return null;
        }
        const [error, res] = await new Promise((resolve) => {
          uni.request({
            url: `http://127.0.0.1:1003/mesWorkshop/findWorkshopIdByManagerId/${userIdInfo.userId}`, 
            method: 'GET',
            success: (response) => resolve([null, response]),
            fail: (err) => resolve([err, null])
          });
        });

        if (error || !res) {
          throw new Error('网络请求失败');
        }

        if (res.statusCode !== 200 || res.data.code !== 200) { 
          throw new Error(res.data.msg || '获取车间ID失败');
        }

        console.log('获取的车间ID：', res.data.data);
        return res.data.data; 
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
        return null;
      }
    },

    // 获取生产列表
    async fetchMessages() {
      try {
        const workshopId = await this.getWorkshopId(); // 获取车间ID
        
        if (!workshopId) {
          uni.showToast({ title: '未选择车间', icon: 'none' });
          return;
        }

        const res = await uni.request({
          url: `http://127.0.0.1:1003/orderScheduling/findList`,
          method: 'GET'
        });

        if (res.statusCode === 200 && res.data.code === 200) {
          const allData = res.data.data || [];
          // 过滤待生产列表（status=2 且属于当前车间）
          this.todoList = allData.filter(item => 
            item.status === 2 && item.workshopsId === workshopId
          );
          // 过滤生产中列表（status=1 且属于当前车间）
          this.doneList = allData.filter(item => 
            item.status === 1 && item.workshopsId === workshopId
          );
        }
      } catch (err) {
        console.error('请求失败', err);
        uni.showToast({ title: '数据加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 计算生产进度
    calcProgress(item) {
      return ((item.allocatedQuantity / item.quantity) * 100).toFixed(0);
    },

    // 计算剩余数量
    calcRemainingQuantity(item) {
      return item.quantity - item.allocatedQuantity; // 剩余数量 = 总数量 - 已分配数量
    }
  }
};
</script>

<style scoped>
.messages-container {
  padding: 20rpx;
  min-height: 100vh;
}

/* 选项卡样式 */
.tab-bar-top {
  display: flex;
  background: #fff;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
  margin-bottom: 20rpx;
}

.tab-bar-top text {
  flex: 1;
  text-align: center;
  padding: 28rpx 0;
  font-size: 30rpx;
  color: #666;
  transition: all 0.3s;
}

.active-tab {
  color: #007aff !important;
  position: relative;
}

.active-tab::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 4rpx;
  background: #007aff;
}

/* 列表项样式 */
.message-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 28rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-code {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.status-tag {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;
}

.todo {
  background: #ffeaea;
  color: #ff4444;
}

.doing {
  background: #e8f4ff;
  color: #007aff;
}

.product-name {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.item-details {
  display: flex;
  flex-direction: column; /* 改为垂直排列 */
  font-size: 26rpx;
  color: #999;
}

.item-details text {
  margin: 4rpx 0; /* 增加间距 */
}

/* 加载提示 */
.loading {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

.empty {
  text-align: center;
  padding: 60rpx;
  color: #ccc;
  font-size: 28rpx;
}
</style>